import * as api from '../../api/api.js';
import * as db from '../../utils/db.js';
import { ASSETS } from '../../config.js';
const app = getApp();
const os = app.os;

Page({
  data: {
    assets: ASSETS,
    showClean: false,
    showHot: true,
    search: {
      search: '',
      is_hot: 0,
      page: 1, 
      limit: 10
    },
    pageTotal: 0,
    isEnd: false,
    isEmpty: false,
    isLoading: true,
    searchHistory: [],
    hotData: [],
    dataList: []
  },

  onLoad: function (options) {
    this.getHotPlayletList();
    let history = db.getSearchHistory();
    if(history){
      this.setData({
        searchHistory: history
      });
    }
  },

  onReady: function () {
    app.sendAppLogs('app', 3); // 日志
  },

  /**
   * 到底部加载
   */
  onReachBottom: function () {
    // this.onloadPageData();
  },

  /**
   * 加载数据
   */
  onloadPageData: function (){
    if(!this.data.showHot){
      let search = this.data.search;
      search.page += 1;
      if (search.page <= this.data.pageTotal){
        this.setData({search: search});
        this.getPlayletList();
      }
    }
  },

  /**
   * 搜索列表
   */
  getPlayletList: function () {
    const that = this;
    // os.showNavigationBarLoading({});
    api.getPlayletList(that.data.search).then(res => {
      // os.hideNavigationBarLoading({});
      let dataList = that.data.dataList;
      let search = that.data.search;
      let isEnd = false;
      let isEmpty = false;
      let isLoading = false;
      if (res.code == 200) {
        if(res.data.current_page == 1){
          dataList = [];
        }
        if(res.data.list.length > 0){
          dataList = dataList.concat(res.data.list);
        }
        if(res.data.current_page >= res.data.total_page && res.data.count > 0){
          isEnd = true;
        }
        if(res.data.current_page < res.data.total_page && res.data.count > 0){
          isLoading = true;
        }
        if(dataList.length == 0){
          isEmpty = true;
        }else{
          const keyword = that.data.search.search;
          const replace = `<span style="color: #f25c40;font-size: 12px">${that.data.search.search}</span>`;
          const replace2 = `<span style="color: #f25c40;">${that.data.search.search}</span>`;
          dataList = dataList.map(item => {
            item.intro = item.intro.replace(new RegExp(keyword, 'g'), replace);
            item.playlet_name = item.playlet_name.replace(new RegExp(keyword, 'g'), replace2);
            return item;
          });
        }

        search.page = parseInt(res.data.current_page);
        that.setData({dataList: dataList, search: search, pageTotal: res.data.total_page,isEnd: isEnd,isLoading: isLoading,isEmpty:isEmpty});
      }else{
        that.setData({isLoading: false,isEmpty:true});
        return app.Tips({title: res.msg});
      }
    }).catch(err => {
      // os.hideNavigationBarLoading({});
      that.setData({isLoading: false,isEmpty:true});
    });
  },

  /**
   * 热搜列表
   */
  getHotPlayletList: function () {
    const that = this;
    os.showNavigationBarLoading({});
    api.getPlayletList({
      is_hot: 1,
      limit: 10
    }).then(res => {
      if (res.code == 200) {
        if(res.data.list.length > 0){
          that.setData({hotData: res.data.list})
        }
      }else{
        return app.Tips({title: res.msg});
      }
      os.hideNavigationBarLoading({});
    }).catch(err => {
      os.hideNavigationBarLoading({});
    });
  },

  /**
   * 点击搜索
   */
  submitSearch: function () {
    this.goSearch(true);
    app.sendAppLogs('app', 4, {
      method_mark: 'search',
      method_mark_1: '搜索'
    });
  },

  /**
   * 点击历史搜索
   */
  goHistorySearch: function (e) {
    const value = e.currentTarget.dataset.value;
    let search = this.data.search;
    search.search = value;
    this.setData({search: search});
    this.goSearch();
  },

  /**
   * 搜索
   */
  goSearch: function (isAddHistory = false) {
    const that = this;
    if(that.data.search.search != ""){
      let search = that.data.search;
      let keyword = that.data.search.search;
      search.page = 1;
      let data = {
        search: search,
        dataList: [],
        showHot: false,
        isEnd: false,
        isEmpty: false
      };

      if(isAddHistory){
        let history = that.data.searchHistory;
        if (history.includes(keyword)) {
          history = history.filter(item => item !== keyword);
        }
        history.unshift(keyword);
        data.searchHistory = history;
        db.updateSearchHistory(history);
      }
      that.setData(data);
      that.getPlayletList();
    }
  },

  /**
   * 跳播放页
   */
  toVideoPage: function (e) {
    app.goPlayVideoPage(e.currentTarget.dataset.item.playlet_id);
  },

  /**
   * 清除历史
   */
  cleanHistory: function () {
    const that = this;
    os.showModal({
      content: "确认删除所有搜索历史？",
      confirmText: "删除",
      cancelText: "取消",
      confirmColor: "#f25c40",
      success(res) {
        if (res.confirm) {
          db.delSearchHistory();
          that.setData({
            searchHistory: []
          });
        }
      }
    });  
  },

  /**
   * 搜索内容变动绑定
   */
  bindSearchInput: function (e) {
    let search = this.data.search;
      search.search = e.detail.value.trim();
    this.setData({
      search: search,
      showClean: search.search == "" ? false:true
    });
  },

  /**
   * 清空搜索内容
   */
  cleanInput: function () {
    let search = this.data.search;
      search.page = 1;
      search.search = '';
    this.setData({
      search: search,
      showHot: true,
      showClean: false
    });
  },

  /**
   * 页面滑动
   */
  onScroll: function(e) {
    this.onSlideEvent(e);
  },

  /**
   * 滑动事件
   */
  onSlideEvent: function(e) {
    if (this.scrollHeight === undefined) {
      this.scrollHeight = [0, 0];
    }
    
    this.scrollHeight[1] = parseInt(e.detail.scrollTop);

    if (this.slideTimeId) {
      clearTimeout(this.slideTimeId);
    }
    
    this.slideTimeId = setTimeout(() => {
      clearTimeout(this.slideTimeId);

      if(this.scrollHeight[0] !== this.scrollHeight[1]){
        app.sendAppLogs('app', 5, {
          method_mark: this.scrollHeight[0],
          method_mark_1: this.scrollHeight[1],
        });
        this.scrollHeight[0] = this.scrollHeight[1];
      }

    }, 300);
  },

  /**
   * 去首页看看
   */
  toHomePage: function(){
    os.switchTab({
      url: '/pages/index/index'
    });
  }
})